package com.imooc.Interceptor;

import com.imooc.base.BaseInfoProperties;
import com.imooc.exception.GraceException;
import com.imooc.result.ResponseStatusEnum;
import com.imooc.utils.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liansen
 * @create 12-23-11:42
 */
public class SMSInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户ip
        String userIp = IPUtil.getRequestIp(request);
        //判断redis中有没有对应的key MOBILE_SMSCODE + ":" + userIp
        Boolean userIpIsExist = redisTemplate.hasKey(MOBILE_SMSCODE + ":" + userIp);
        if(userIpIsExist){
//            System.out.println("短信发送频率发送太高, 请稍后再试");
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
